package room

import (
	"fmt"
	"sync"
	"time"

	"mmo/card/internal/config"
)

type PlayerState struct {
	ID      string
	Deck    []string
	Hand    []string
	Discard []string
}

type GameRoom struct {
	ID        string
	Capacity  int
	players   map[string]*PlayerState
	State     *GameState
	createdAt time.Time
	mu        sync.RWMutex
	cfg       config.GameConfig
}

func NewGameRoom(id string, capacity int, cfg config.GameConfig) *GameRoom {
	return &GameRoom{
		ID:        id,
		Capacity:  capacity,
		players:   make(map[string]*PlayerState),
		State:     &GameState{Phase: PhaseWaiting},
		createdAt: time.Now(),
		cfg:       cfg,
	}
}

func (r *GameRoom) Join(playerID string) (*GameRoom, error) {
	r.mu.Lock()
	defer r.mu.Unlock()
	if _, ok := r.players[playerID]; ok {
		return r, ErrAlreadyInRoom
	}
	if len(r.players) >= r.Capacity {
		return r, ErrRoomFull
	}
	ps := &PlayerState{
		ID:   playerID,
		Deck: defaultDeck(r.cfg.MaxDeckSize),
	}
	drawStartingHand(ps, r.cfg.StartingHandSize)
	r.players[playerID] = ps

	// 简单开局：当人数>=2且在等待阶段则进入游戏
	if len(r.players) >= 2 && r.State.Phase == PhaseWaiting {
		r.State.Phase = PhasePlaying
		r.State.TurnStartedAt = time.Now()
		r.State.TurnPlayerID = playerID // 简化：最近加入者先手
		r.State.TurnDeadline = r.State.TurnStartedAt.Add(time.Duration(r.cfg.TurnDurationSeconds) * time.Second)
	}
	return r, nil
}

func (r *GameRoom) Leave(playerID string) (*GameRoom, error) {
	r.mu.Lock()
	defer r.mu.Unlock()
	delete(r.players, playerID)
	if len(r.players) == 0 {
		r.State.Phase = PhaseWaiting
		r.State.TurnPlayerID = ""
	}
	return r, nil
}

func defaultDeck(max int) []string {
	deck := make([]string, 0, max)
	for i := 1; i <= max; i++ {
		deck = append(deck, fmt.Sprintf("C%03d", i))
	}
	return deck
}

func drawStartingHand(ps *PlayerState, n int) {
	if n > len(ps.Deck) {
		n = len(ps.Deck)
	}
	ps.Hand = append(ps.Hand, ps.Deck[:n]...)
	ps.Deck = ps.Deck[n:]
}
